package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClient;

    /**
     * 启动 TM(Transaction Manager)
     * 链接事务协调器 TC(Transaction Coordinator, Seata Server)
     * 注册全局事务
     * 启动 RM(Resource Manager)
     * @param order
     */
    @GlobalTransactional
    @Override
    public void create(Order order) {
        // 从全局唯一id发号器获得id，这里暂时随机产生一个 orderId
        String orderId = easyIdClient.nextId("order_business");
        order.setId(Long.parseLong(orderId));

        orderMapper.create(order);

        log.info("保存订单成功,order"+order);
        // 调用storage，修改库存
        storageClient.decrease(order.getProductId(), order.getCount());
        // 调用account，修改账户余额
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
